package com.rlyy.basic.trace;

import com.alibaba.fastjson.JSONObject;
import com.rlyy.common.param.LinkTrace;
import com.rlyy.common.param.Request;
import com.rlyy.basic.utils.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author yuanqinglong
 * @since 2021/10/12 16:04
 */
@Component
@EnableAsync
public class DefaultTraceProcessor implements ITraceProcess {

    /**
     * 失败
     */
    public static final String FAILURE = "FAILURE";
    /**
     * 成功的
     */
    public static final String SUCCESSFUL = "SUCCESSFUL";

    static final Logger logger = LoggerFactory.getLogger("trace");


    /**
     * 获取服务名称 名称未配置 获取服务端口号
     */
    @Value("#{'${spring.application.name:}'.empty ? '${grpc.server.port}' : '${spring.application.name:}'}")
    private String appId;


    @Override
    public LinkTrace tracking(TraceCombination traceCombination) {
        Request request = traceCombination.getRequest();
        LinkTrace linkTrace = request.getLinkTrace();
        if (linkTrace == null) {
            linkTrace = new LinkTrace(UUIDUtil.getUUID(), UUIDUtil.getUUID(), null, request.getApiId(), appId, null, null, SUCCESSFUL);
        } else {
            linkTrace = new LinkTrace(linkTrace.getTraceId(), UUIDUtil.getUUID(), linkTrace.getSpanId(), request.getApiId(), appId, null, linkTrace.getTimestamp(), SUCCESSFUL);
        }
        TraceContextHolder.setTraceAttributes(linkTrace);
        request.setLinkTrace(linkTrace);
        return linkTrace;
    }


    @Override
    public void syncPrintTracking(LinkTrace linkTrace) {
        printTracking(linkTrace);
        //MDC.remove("tid");
    }



    /**
     * 同步保存跟踪
     *
     * @param linkTrace 链接跟踪
     */
    public void printTracking(LinkTrace linkTrace) {
        TraceContextHolder.resetRequestAttributes();
        MDC.put("tid", linkTrace.getTraceId());
        String trace = JSONObject.toJSONString(linkTrace);
        if (Objects.equals(linkTrace.getResult(), SUCCESSFUL)) {
            logger.info(trace);
        }
        if (Objects.equals(linkTrace.getResult(), FAILURE)) {
            logger.error(trace);
        }
    }


}
